package dubbo.learn.transport.mina;

import com.alibaba.fastjson.JSONObject;
import dubbo.learn.common.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;

import java.util.concurrent.CompletableFuture;

@Slf4j
public class CustomMinaHandler extends IoHandlerAdapter {

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        log.info("sessionOpened");
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        log.info("sessionClosed");
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        log.info("mina client,current thread:{}," +
                        "CustomMinaHandler messageReceived:{}",
                Thread.currentThread().getName(),
                message);
        ResponseVO responseVO = JSONObject.parseObject((String) message, ResponseVO.class);
        String requestId = responseVO.getRequestId();

        //获取future
        CompletableFuture<Object> completableFuture =
                MinaClientRpcInvoker.requestId2futureMap
                .get(requestId);
        completableFuture.complete(responseVO.getContent());
        log.info("客户端端读写远程地址是-----------"
                + session.getRemoteAddress() + "信息是：" + message.toString());
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        log.info("messageSent");
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        log.info("exceptionCaught");
    }
}
